package com.xms.security.api.controller;

import com.xms.security.entity.Privilege;
import com.xms.security.service.sitemap.IPrivilegeFinderService;
import com.xms.security.service.sitemap.IPrivilegeTreeBuilder;
import com.xms.security.service.sitemap.IPrivilegeUpdaterService;
import com.xms.utils.CollectionUtil;
import com.xms.web.framework.controller.ApiBaseController;
import com.xms.web.framework.model.JsonResultObject;
import com.xms.web.framework.model.UpdateAuthorizationStateModel;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * MenuAuthorizationController
 * </p>
 *
 * @author migo
 * @since 2021/10/20
 */
@RestController
@RequestMapping("/{org}/api/security/menu")
public class MenuAuthorizationController extends ApiBaseController {
    private IPrivilegeFinderService _privilegeFinderService;
    private IPrivilegeUpdaterService _privilegeUpdaterService;
    private IPrivilegeTreeBuilder _privilegeTreeBuilder;

    public MenuAuthorizationController(IPrivilegeFinderService privilegeFinderService,
                                       IPrivilegeUpdaterService privilegeUpdaterService,
                                       IPrivilegeTreeBuilder privilegeTreeBuilder) {
        _privilegeFinderService = privilegeFinderService;
        _privilegeUpdaterService = privilegeUpdaterService;
        _privilegeTreeBuilder = privilegeTreeBuilder;
    }

    @ApiOperation("查询菜单权限资源")
    @GetMapping("privilegeresource")
    public JsonResultObject privilegeResource() {
        String result = _privilegeTreeBuilder.build(null);
        return JOk(result);
    }

    @ApiOperation("启用菜单权限")
    @PostMapping("authorizationenabled")
    public JsonResultObject authorizationEnabled(UpdateAuthorizationStateModel model) {
        List<Privilege> authorizations = _privilegeFinderService.getAuthorizations();
        if (CollectionUtil.notEmpty(authorizations)) {
            _privilegeUpdaterService.updateAuthorization(false, authorizations.stream().map(x -> x.getPrivilegeid()).collect(Collectors.toList()));
        }
        if (CollectionUtil.notEmpty(model.objectId)) {
            _privilegeUpdaterService.updateAuthorization(true, model.objectId);
        }
        return JSaveSuccess();
    }
}
